var collectionHolder = $('ul.groups');
var addGroupLink = $('<a href="#" class="add_group_link">Add a group</a>');
var newLinkLi = $('<li></li>').append(addGroupLink);
var idCounter = 1;

jQuery(document).ready(function() {
	    collectionHolder.find('li').each(function() {
			addGroupDeleteLink($(this));
		});
		collectionHolder.append(newLinkLi);

		addGroupLink.on('click', function(e) {
			e.preventDefault();
			addGroupForm(collectionHolder, newLinkLi);
		});
});
function addGroupForm(collectionHolder, newLinkLi) {
    var prototype = collectionHolder.attr('data-prototype');

    var newIndex = idCounter + collectionHolder.find(':input').length;
    var newForm = prototype.replace(/__name__/g, newIndex);
	var $newFormLi = $('<li></li>').append(newForm);
	addGroupDeleteLink($newFormLi);
	newLinkLi.before($newFormLi);
	
	idCounter++;
}
function addGroupDeleteLink($li){
	var delLink = $('<a href="#">&times;</a>');
	$li.append(delLink);
	delLink.on('click', function(e) {
		e.preventDefault();
		$li.remove();
	});
}